﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using LsUpdater.API;
using System.Threading;
using System.Diagnostics;
using System.IO;
using System.Xml;

namespace LsUpdater
{
    public partial class loading : Form
    {
        public loading()
        {
            InitializeComponent();
            this.Load += new EventHandler(loading_Load);
        }  

        Thread thread = null;
        void loading_Load(object sender, EventArgs e)
        {
            CheckForIllegalCrossThreadCalls = false;
            thread = new Thread(new ThreadStart(ReadConfig));
            thread.Start();

        }

        private UpdateInfo XmlToList(string xmlfile)
        {
            UpdateInfo info = new UpdateInfo();
            try
            {
                XmlNode node = XMLHelper.GetXmlNodeByXpath(xmlfile, "updater/info");
                info.appname=node.SelectSingleNode("appname").InnerText;
                info.ProcessName = node.SelectSingleNode("processname").InnerText;
                info.xmlurl = node.SelectSingleNode("xmlurl").InnerText;
                info.version = node.SelectSingleNode("version").InnerText;
                info.RemoteDir = node.SelectSingleNode("remotedir").InnerText;
                info.datetime = node.SelectSingleNode("datetime").InnerText;
                info.isMustUpdate = node.SelectSingleNode("isMustUpdate").InnerText == "0" ? false : true;
                info.desc = node.SelectSingleNode("desc").InnerText;
                List<UpdateFile> listf = new List<UpdateFile>();
                XmlNodeList nodelist = XMLHelper.GetXmlNodeListByXpath(xmlfile, "updater/files/file");
                foreach (XmlNode item in nodelist)
                {
                    UpdateFile file = new UpdateFile();
                    file.path = item.SelectSingleNode("path").InnerText;
                    file.version = item.SelectSingleNode("version").InnerText;
                    listf.Add(file);
                }
                info.UpdateFiles = listf;
            }
            catch (Exception ex)
            {
                //MessageBox.Show("获取远程更新文件失败!");
                MessageBox.Show(ex.Message);
                Environment.Exit(0);
                return null;
            }
            return info;
        }

        #region 手动检测更新   
        private void ReadConfig()
        {
            Comm.listc.Clear();
            Comm.listClearList.Clear();            
            if (!File.Exists(Application.StartupPath + "\\update.xml"))
            {
                //如果本地没有update.xml文件,则生成一个.
                #region 生成update.xml

                //生成update.xml
                StringBuilder str = new StringBuilder();
                str.Append("<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n");
                str.Append("<updater>\r\n");
                str.Append("<info>\r\n");
                str.Append("<appname>dodiv编辑器</appname>\r\n");
                str.Append("<processname>dodiv编辑器</processname>\r\n");
                str.Append("<xmlurl>http://www.zhanzhebian.com/soft/update\\update.xml</xmlurl>\r\n");               
                str.Append("<remotedir>http://www.zhanzhebian.com/soft/update/</remotedir>");
                str.Append("<version>1.0.0.1</version>\r\n");
                str.Append("<datetime>2011-2-16</datetime>\r\n");
                str.Append("<isMustUpdate>0</isMustUpdate>\r\n");
                str.Append("<desc><![CDATA[]]></desc>");

                DirectoryInfo dir = new DirectoryInfo(Application.StartupPath);
                foreach (FileInfo item in dir.GetFiles())
                {
                    if (item.Extension != ".xml")
                    {
                        FileVersionInfo myFileVersion = FileVersionInfo.GetVersionInfo(item.FullName);
                        String strFileVersion = string.Format("{0}.{1}.{2}.{3}", myFileVersion.FileMajorPart, myFileVersion.FileMinorPart, myFileVersion.FileBuildPart, myFileVersion.FilePrivatePart);
                        //string strFileVersion = myFileVersion.FileVersion;
                        str.Append("<file>\r\n");
                        str.Append("<path>" + item.Name + "</path>\r\n");
                        str.Append("<version>" + strFileVersion + "</version>\r\n");
                        str.Append("</file>\r\n");
                    }
                }
                str.Append("</updater>");
                FileHelper.WriteFile(Application.StartupPath + "\\update.xml", str.ToString(), "utf-8");
                #endregion
            }

            //比较服务器上版本 
            //List<UpdateFile> listRemote = XmlToList("http://www.zhanzhebian.com\\update.xml").UpdateFiles;
            UpdateInfo infoLocal = XmlToList(Application.StartupPath + "\\update.xml");
            Comm.infoRemote = XmlToList(infoLocal.xmlurl);
            
            if (Comm.infoRemote.version == infoLocal.version)
            {
                //不需要升级
                this.Hide();
                MessageBox.Show("当前已经是最新版本,不需要升级!", "升级提示", MessageBoxButtons.OK);
                Environment.Exit(0);
                return;
            }
            List<UpdateFile> listRemote =Comm.infoRemote.UpdateFiles;
            List<UpdateFile> listLocal = infoLocal.UpdateFiles;

            foreach (var remoteitem in listRemote)
            {
                //如果本地有和远程相同的文件,版本号不同,更新它
                if (listLocal.Exists(item => item.path == remoteitem.path && item.version != remoteitem.version) )
                {
                    Comm.listc.Add(remoteitem);
                }
                else if (!listLocal.Exists(item => item.path == remoteitem.path))//如果不存在.下载更新到本地
                {
                    Comm.listc.Add(remoteitem);
                }
            }

            #region 遍历需要删除的文件
            //遍历需要删除的文件
            foreach (var localitem in listLocal)
            {
                if (!listRemote.Exists(item => item.path == localitem.path) && localitem.path.ToLower().Contains(".dll"))                
                {
                    Comm.listClearList.Add(localitem);
                }
            }
            #endregion

            this.Close();
            Application.Run(new UpdaterFrm());
            thread = null;
        }
        #endregion
        
    }

}
